#!/bin/bash

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

# 日志文件
LOG_FILE="/tmp/audio_fix.log"
echo "" > $LOG_FILE

# 记录日志
log() {
    echo -e "$1" | tee -a $LOG_FILE
}

# 检查音频系统状态
check_audio_status() {
    local issues=()
    
    # 检查 PulseAudio 进程
    if ! pgrep -x pulseaudio >/dev/null; then
        issues+=("PulseAudio 进程未运行")
    fi
    
    # 检查声卡
    if ! aplay -l | grep -q "card"; then
        issues+=("未检测到声卡")
    fi
    
    # 检查 ALSA 状态
    if ! amixer > /dev/null 2>&1; then
        issues+=("ALSA 混音器访问失败")
    fi
    
    # 检查用户权限
    if ! groups | grep -qE "audio|pulse|pulse-access"; then
        issues+=("用户缺少音频权限")
    fi
    
    # 检查配置文件
    if [ ! -f ~/.config/pulse/daemon.conf ]; then
        issues+=("PulseAudio 配置文件缺失")
    fi
    
    echo "${issues[@]}"
}

# 自动修复音频系统
fix_audio_system() {
    log "${YELLOW}开始自动修复音频系统...${NC}"
    
    # 1. 安装必要的包
    log "正在安装音频组件..."
    sudo apt-get update -qq
    sudo apt-get install -y -qq pulseaudio pulseaudio-utils alsa-utils pavucontrol
    
    # 2. 配置用户权限
    log "配置用户权限..."
    sudo usermod -aG audio,pulse,pulse-access $USER
    
    # 3. 停止所有音频进程
    log "停止现有音频进程..."
    pulseaudio -k || true
    killall -9 pulseaudio || true
    sleep 2
    
    # 4. 重置配置
    log "重置音频配置..."
    rm -rf ~/.config/pulse/* ~/.pulse/* /tmp/pulse-* || true
    
    # 5. 创建新配置
    mkdir -p ~/.config/pulse
    cat > ~/.config/pulse/daemon.conf << EOF
default-sample-format = float32le
default-sample-rate = 44100
alternate-sample-rate = 48000
default-sample-channels = 2
default-channel-map = front-left,front-right
default-fragments = 4
default-fragment-size-msec = 25
resample-method = speex-float-1
enable-remixing = yes
high-priority = yes
nice-level = -11
realtime-scheduling = yes
exit-idle-time = -1
EOF

    cat > ~/.config/pulse/client.conf << EOF
autospawn = yes
daemon-binary = /usr/bin/pulseaudio
extra-arguments = --log-target=syslog --verbose
enable-shm = yes
EOF

    # 6. 重启 ALSA
    log "重启 ALSA..."
    sudo alsactl restore
    
    # 7. 重新加载声卡模块
    log "重新加载声卡模块..."
    sudo modprobe -r snd_hda_intel || true
    sudo modprobe snd_hda_intel || true
    
    # 8. 启动 PulseAudio
    log "启动 PulseAudio..."
    pulseaudio --start --verbose --log-target=syslog
    sleep 3
    
    # 9. 生成诊断报告
    generate_report
}

# 生成诊断报告
generate_report() {
    log "\n${GREEN}=== 音频系统诊断报告 ===${NC}"
    
    # 检查 PulseAudio 状态
    if pulseaudio --check; then
        log "PulseAudio 状态: ${GREEN}运行中${NC}"
    else
        log "PulseAudio 状态: ${RED}未运行${NC}"
    fi
    
    # 检查声卡
    log "\n声卡信息:"
    aplay -l || log "${RED}未检测到声卡${NC}"
    
    # 检查音频设备
    log "\n输出设备:"
    pactl list short sinks || log "${RED}无输出设备${NC}"
    
    log "\n输入设备:"
    pactl list short sources || log "${RED}无输入设备${NC}"
    
    # 检查音量
    log "\n音量设置:"
    amixer get Master || log "${RED}无法获取音量信息${NC}"
    
    # 检查模块
    log "\n加载的模块:"
    pactl list modules short || log "${RED}无法获取模块信息${NC}"
    
    # 检查最终状态
    local issues=$(check_audio_status)
    if [ -z "$issues" ]; then
        log "\n${GREEN}音频系统修复完成，未发现问题${NC}"
    else
        log "\n${RED}仍存在以下问题：${NC}"
        for issue in "${issues[@]}"; do
            log "- $issue"
        done
    fi
    
    log "\n完整日志已保存至: $LOG_FILE"
}

# 主程序
main() {
    # 检查是否为 root
    if [ "$EUID" -eq 0 ]; then 
        log "${RED}请不要使用 root 用户运行此脚本${NC}"
        exit 1
    fi
    
    # 检查系统
    if ! command -v pulseaudio >/dev/null; then
        log "${YELLOW}系统中未安装 PulseAudio，将进行安装...${NC}"
    fi
    
    # 执行修复
    fix_audio_system
}

# 执行主程序
main
